package com.chaber.containers.aspects;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import com.chaber.containers.beans.AbstractObjectData;
import com.chaber.containers.common.MessageEvent;
import com.chaber.containers.services.AbstractService;

@Aspect
public class MessagePublisherAspect {

	@Pointcut("execution(* com.chaber.containers.services.AbstractService+.*save*(..))")
	public void pointcutSaveEntity() {}

	@Pointcut("execution(* com.chaber.containers.services.AbstractService+.*remove*(..))")
	public void pointcutRemoveEntity() {}
	
	@AfterReturning("pointcutSaveEntity() && args(abstractObject)")
	public void afterSaveEntity(JoinPoint joinPoint, AbstractObjectData abstractObject) {
		Object target = joinPoint.getTarget();

		AbstractService service = (AbstractService) target;

		MessageEvent messageEvent = new MessageEvent(service);
		String objName = abstractObject.getClass().getSimpleName().replaceAll("Data", "");
		messageEvent.setMessage("The " + objName + " has been saved");

		service.getEventPublisher().publishEvent(messageEvent);
	}

	@AfterReturning("pointcutRemoveEntity() && args(entityId)")
	public void afterRemoveEntity(JoinPoint joinPoint, Object entityId) {
		Object target = joinPoint.getTarget();

		AbstractService service = (AbstractService) target;

		MessageEvent messageEvent = new MessageEvent(service);
		messageEvent.setMessage("The entity with identifier: '" + entityId + "' has been removed");

		service.getEventPublisher().publishEvent(messageEvent);
	}
}
